package com.zzyy.study.consumer;

import com.zzyy.study.common.BusinessExceptionUtils;
import com.zzyy.study.config.RabbitMQConfiguration;
import com.zzyy.study.entities.OrderPO;
import com.zzyy.study.mq.consumer.AbstractIdempotentConsumer;
import com.zzyy.study.mq.dto.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 按理来说需要单独新建一个boot微服务作为消费者，此处偷懒，直接用OrderConsumer单独一个类
 * 作为消费者模拟通过。
 * @auther zzyy
 * @create 2024-08-24 22:48
 */
@Slf4j
@Component
public class OrderConsumer extends AbstractIdempotentConsumer<OrderPO, Msg<OrderPO>>
{
    AtomicInteger atomicInteger = new AtomicInteger();

    @RabbitListener(queues = RabbitMQConfiguration.Order.QUEUE) //方式一
    //@RabbitListener(queues = RabbitMQConfiguration.QUEUE) //方式二
    public void dispose(Message message) {
        super.dispose(message);
    }

    /**
     * 订单金额为负为零时error,会抛出一个异常，会触发衰减式消费重试的逻辑。
     * @param message 原始消息
     * @param body    消息体
     */
    @Override
    protected void disposeIn(Message message, OrderPO body)
    {
        String consumerQueue = message.getMessageProperties().getConsumerQueue();
        log.info("从RabbitMQ收到订单消息：{},队列名字:{}", body,consumerQueue);
        atomicInteger.getAndIncrement();


        //故意使坏使坏，金额为负为零时故意出错抛出异常
        if (body.getPrice().signum() <= 0)
        {
            System.out.println("消费者重复消费了多少次: "+atomicInteger.get());
            throw BusinessExceptionUtils.businessException("订单金额为负为零时error");
        }
    }
}
